#include <jni.h>
#include <string>
#include "LyTool.h"
#include "LyLogPrint.h"
#include "LogWriter.h"

LogWriter *logWriter;


/**
 * 在指定的目录下，返回合适的日志文件路径(文件可能是新建的或已有的，未存满就不用新建)
 */
extern "C"
JNIEXPORT jstring JNICALL
Java_com_szlanyou_lylog_tool_LyLogSaveTool_nativeInit(JNIEnv *env,
                                                      jobject thiz,
                                                      jstring dir) {


    std::string logDir = jstring2string(env, dir);
    LOGD("地址logDir=%s", logDir.c_str());
    env->DeleteLocalRef(dir);

    logWriter = new LogWriter();
    ErrorInfo *errInfo = logWriter->init(env, logDir);
    jboolean initSuccess = errInfo == nullptr;
    if (!initSuccess) {
        showLog("初始化失败,%d,%s", errInfo->errCode, errInfo->errMsg);
    }
    delete errInfo;
    return env->NewStringUTF(logWriter->filePath.c_str());
}


/**
 * 将字符串内容写入日志文件中。
 * @return 返回写入的操作结果
 */
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_szlanyou_lylog_tool_LyLogSaveTool_nativeWrite(JNIEnv *env, jobject thiz,
                                                       jstring msg_content) {

    if (msg_content == nullptr) {
        return false;
    }

    const char *msg = env->GetStringUTFChars(msg_content, JNI_FALSE);
    ErrorInfo *errInfo = logWriter->writeLog(env, msg);
    env->ReleaseStringUTFChars(msg_content, msg);

    jboolean writeSuccess = errInfo == nullptr;
    if (!writeSuccess) {
        showLog("写入失败,%d,%s", errInfo->errCode, errInfo->errMsg);
    }

    delete errInfo;
    return writeSuccess;
}

